﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Report.Properties;

namespace Report.Service
{
    public class HttpService
    {
        private CookieContainer cookieContainer = new CookieContainer();

        public CookieContainer CookieContainer
        {
            get { return cookieContainer; }
            set { cookieContainer = value; }
        }

        static HttpService()
        {
            ServicePointManager.Expect100Continue = false;
        }

        public HttpWebRequest ConfigWebRequest(string url)
        {
            return ConfigWebRequest(url, null);
        }

        public HttpWebRequest ConfigWebRequest(string url, Dictionary<string, string> postData)
        {
            var request = (HttpWebRequest) WebRequest.Create(url);
            request.CookieContainer = cookieContainer;
            request.UserAgent = Settings.Default.UserAgent;
            request.Accept = Settings.Default.AcceptHeader;
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Method = postData != null && postData.Count>0 ? "POST" : "GET";

            if (postData != null && postData.Count>0)
            {
                var parameterBuilder = new StringBuilder();
                foreach (var keypair in postData)
                {
                    parameterBuilder.AppendFormat("{0}={1}&", keypair.Key, keypair.Value);
                }
                string data = parameterBuilder.ToString().TrimEnd('&');

                request.ContentType = "application/x-www-form-urlencoded";
                byte[] binaryData = Encoding.UTF8.GetBytes(data);
                request.GetRequestStream().Write(binaryData, 0, binaryData.Length);
                request.GetRequestStream().Close();
            }

            return request;
        }
        
        public string ExecuteRequestAsString(HttpWebRequest webRequest)
        {
            byte[] data = ExecuteRequest(webRequest);
            return Encoding.UTF8.GetString(data);
        }

        public byte[] ExecuteRequest(HttpWebRequest webRequest)
        {
            try
            {
                var response = (HttpWebResponse) webRequest.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var contentLength = (int) response.ContentLength;
                    var buffer = new byte[contentLength];

                    using (Stream stream = response.GetResponseStream())
                    {
                        int readed = 0;
                        while (readed < contentLength)
                        {
                            int len = stream.Read(buffer, readed, contentLength - readed);
                            if (len == 0) break;
                            readed += len;
                        }
                    }
                    if ("gzip".Equals(response.ContentEncoding, StringComparison.CurrentCultureIgnoreCase))
                    {
                        buffer = CompressHelper.GzipDeCompress(buffer);
                    }
                    if ("deflate".Equals(response.ContentEncoding, StringComparison.CurrentCultureIgnoreCase))
                    {
                        buffer = CompressHelper.DeflateDeCompress(buffer);
                    }
                    return buffer;
                }
                return null;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}